package com.carey.blog.framework.latke.util;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.carey.blog.framework.latke.model.User;

/**
 * Session utilities.
 * 
 */
public final class Sessions {

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger.getLogger(Sessions.class
			.getName());

	/**
	 * Private default constructor.
	 */
	private Sessions() {
	}

	/**
	 * Logins the specified user from the specified request.
	 * 
	 * @param request
	 *            the specified request
	 * @param userName
	 *            the specified user name
	 * @param userPwd
	 *            the specified user password(MD5 hash)
	 */
	public static void login(final HttpServletRequest request,
			final String userName, final String userPwd) {
		final HttpSession session = request.getSession();

		session.setAttribute(User.USER_NAME, userName);
		session.setAttribute(User.USER_PASSWORD, userPwd);
	}

	/**
	 * Logout a user with the specified request.
	 * 
	 * @param request
	 *            the specified request
	 * @return {@code true} if succeed, otherwise returns {@code false}
	 */
	public static boolean logout(final HttpServletRequest request) {
		final HttpSession session = request.getSession(false);

		if (null != session) {
			final String userName = (String) session
					.getAttribute(User.USER_NAME);

			if (!Strings.isEmptyOrNull(userName)) {
				session.invalidate();

				return true;
			}
		}

		return false;
	}

	/**
	 * Gets the current logged in user password with the specified request.
	 * 
	 * @param request
	 *            the specified request
	 * @return the current user password or {@code null}
	 */
	public static String currentUserPwd(final HttpServletRequest request) {
		final HttpSession session = request.getSession(false);

		if (null != session) {
			return (String) session.getAttribute(User.USER_PASSWORD);
		}

		return null;
	}

	/**
	 * Gets the current logged in user name with the specified request.
	 * 
	 * @param request
	 *            the specified request
	 * @return the current user name or {@code null}
	 */
	public static String currentUserName(final HttpServletRequest request) {
		final HttpSession session = request.getSession(false);

		if (null != session) {
			return (String) session.getAttribute(User.USER_NAME);
		}

		return null;
	}
}
